import axios from 'axios'
import { Toast, Dialog } from 'vant';
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import { removeUser } from '@/utils/user'
import { getQueryVariable, getIndexUrl } from '@/utils/app'
import package_config from '../../package.json'

const API_ROOT = process.env.VUE_APP_AXIOS_URL
// create an axios instance
const service = axios.create({
  baseURL: API_ROOT, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    //add app_id
    // if(store.state.app) {
    //   let app_id = store.state.app.id
    //   if(app_id)config.data = {app_id, ...config.data}
    //   if(config.method == 'get') {
    //     config.params = {app_id, ...config.data}
    //   }
    // }
    // config.headers['Content-Type'] = 'application/json'
    config.url += '?v=' + package_config.version
    let token = getToken();
    if(token)config.headers['Authorization'] = 'Bearer ' + getToken()
    let app = 'dt'
    let q = process.env.VUE_APP_Q
    config.data = {app, q, ...config.data}

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 200 && res.status !== 201) {
      Toast({
        message: res.message || 'Error',
        onClose: data=> {
          if(res.status == 304) {
            window.location.href = getIndexUrl(store.state.acc.code)
            return res;
          }else if(res.status == 401) {
            console.log(res)
            removeToken()
            removeUser()
            window.location.href = getIndexUrl(store.state.acc.code)
            return res;
          }
        }
      });
      
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.status === 50008 || res.status === 50012 || res.status === 50014) {
        // to re-login
        Dialog.alert({
          title: 'Confirm logout',
          message: 'You have been logged out, you can cancel to stay on this page, or log in again'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        });
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.data
    }
  },
  error => {
    console.log(error) // for debug
    if(error.response) {
      Toast(error.response.data.message);
    }else{
      Toast('网络错误，请关闭页面，重新打开');
    }
    return Promise.reject(error)
  }
)

export default service
